/****************************************************************************
 * 2025.4 小管
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using System.Linq;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class CoinUpgradePanel : UIElement, IController
	{
		private void Awake()
		{
			CoinUpgradeItemTemplate.Hide();

			Global.Coin.RegisterWithInitValue(coin =>
			{
				CoinText.text = "金币：" + coin;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			foreach (var coinUpgradeItem in this.GetSystem<CoinUpgradeSystem>().Items.Where(item => !item.UpgradeFinish))
			{
				CoinUpgradeItemTemplate.InstantiateWithParent(CoinUpgradeItemRoot)
				.Self((self) =>
				{
					var itemCache = coinUpgradeItem;
					self.GetComponentInChildren<Text>().text = coinUpgradeItem.Description + $" {coinUpgradeItem.Price} 金币";
					self.onClick.AddListener(() =>
					{
						itemCache.Upgrade();
						AudioKit.PlaySound("AbilityLevelUp");
					});
					var selfCache = self;
					coinUpgradeItem.OnChange.Register(() =>
					{
						if(itemCache.ConditionCheck())
						{
							selfCache.Show();
						}
						else
						{
							selfCache.Hide();
						}
					}).UnRegisterWhenGameObjectDestroyed(selfCache);
					
					if(itemCache.ConditionCheck())
					{
						selfCache.Show();
					}
					else
					{
						selfCache.Hide();
					}
					Global.Coin.RegisterWithInitValue(coin =>
					{
						if(coin >= itemCache.Price)
						{
							selfCache.interactable = true;
						}
						else
						{
							selfCache.interactable = false;
						}
						CoinText.text = "金币：" + coin;
						
					}).UnRegisterWhenGameObjectDestroyed(self);
				});

				BtnClose.onClick.AddListener(()=>
				{
					AudioKit.PlaySound(Sfx.BUTTONCLICK);
					this.Hide();
				});
			}
		}

		protected override void OnBeforeDestroy()
		{
		}

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}